package com.jsbb.controller.tool;

import com.alibaba.fastjson.JSON;
import com.jsbb.annotation.ApiLog;
import com.jsbb.common.Message;
import com.jsbb.config.ParamsConfig;
import com.jsbb.dto.tool.TableExportDto;
import com.jsbb.dto.tool.TableQueryDto;
import com.jsbb.service.tool.TableService;
import com.jsbb.util.EnvironmentUtils;
import com.jsbb.util.WordUtils;
import com.jsbb.vo.tool.TableListVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 数据库表Controller
 *
 * @author w
 * @date 2021-03-05
 */
@Slf4j
@RestController
@RequestMapping("/tool/table")
@ApiLog("数据库表")
@Api(tags = {"3.2 工具管理-数据库表"})
public class TableController {

    @Autowired
    private TableService tableService;

    @Autowired
    private ParamsConfig paramsConfig;

    @PostMapping("/list")
    @ApiOperation(value = "获取列表")
    public Message<List<TableListVo>> list(@RequestBody TableQueryDto queryDto) {
        if (queryDto.getIp().isEmpty() ||
                queryDto.getPort().isEmpty() ||
                queryDto.getSchema().isEmpty() ||
                queryDto.getUser().isEmpty() ||
                queryDto.getPassword().isEmpty()) {
            queryDto.setIp(EnvironmentUtils.getDsIp());
            queryDto.setPort(EnvironmentUtils.getDsPort());
            queryDto.setSchema(EnvironmentUtils.getDsSchema());
            queryDto.setUser(EnvironmentUtils.getDsUser());
            queryDto.setPassword(EnvironmentUtils.getDsPassword());
        }
        List<TableListVo> pageVo = tableService.list(queryDto);
        return Message.success(pageVo);
    }

    @PostMapping("/export")
    @ApiOperation(value = "导出")
    public void export(@Validated @RequestBody TableExportDto exportDto, HttpServletResponse response) {
        if (exportDto.getIp().isEmpty() ||
                exportDto.getPort().isEmpty() ||
                exportDto.getSchema().isEmpty() ||
                exportDto.getUser().isEmpty() ||
                exportDto.getPassword().isEmpty()) {
            exportDto.setIp(EnvironmentUtils.getDsIp());
            exportDto.setPort(EnvironmentUtils.getDsPort());
            exportDto.setSchema(EnvironmentUtils.getDsSchema());
            exportDto.setUser(EnvironmentUtils.getDsUser());
            exportDto.setPassword(EnvironmentUtils.getDsPassword());
        }
        Map<String, Object> dbInfo = JSON.parseObject(JSON.toJSONString(exportDto), Map.class);
        WordUtils.exportDbTable(dbInfo, response);
    }
}
